package com.ztesoft.test.service.processer;

import java.net.URLEncoder;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.HttpKit;
import com.ztesoft.ip.entity.BaiduMap;
import com.ztesoft.ip.utils.PropertiesUtil;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * @author code4crafter@gmail.com <br>
 */
public class NewProcessor implements PageProcessor {

	public static final String URL_LIST = "http://www\\.harveynichols\\.com/mens-new-in/#/number_of_days_range/last_28_days/page/.";

	public static final String URL_POST = "http://www\\.harveynichols\\.com/./";

	private Site site = Site.me().setDomain("harveynichols.com").setSleepTime(3000).setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");

	@Override
	public void process(Page page) {
		// 列表页
		if (page.getUrl().regex(URL_LIST).match()) {
			System.out.println(1);
			page.addTargetRequests(page.getHtml().xpath("//a[@class='product-image js-item-wrap js-has-outfit']").links().regex(URL_POST).all());
			page.addTargetRequests(page.getHtml().links().regex(URL_LIST).all());
			// 文章页
		} else {
			System.out.println(2);
			String name = page.getHtml().xpath("//div[@class='product-main-info']/div[@class='product-name']/h1/text()").toString();
			System.out.println(name);
			String address = page.getHtml().xpath("//div[@class='product-main-info']/div[@class='price-box']/span[@class='price']/text()").toString();

			System.out.println(address);

			String phone = page.getHtml().xpath("//div[@class='imageslider']/ul[@id='imageslider']/li[2]").get();
			System.out.println(phone);

		}
	}

	private String getLocation(String address) {
		// TODO Auto-generated method stub
		PropertiesUtil.load("resouce/config", "value.config");

		String baidu_address = "http://api.map.baidu.com/place/v2/search?ak=" + PropertiesUtil.getProperty("baiak") + "" + "&output=json&query=" + address + "&page_size=1&page_num=0&scope=1&region=" + "银川";
		// System.out.println(baidu_address);
		BaiduMap map = JSON.parseObject(HttpKit.get(baidu_address), BaiduMap.class);
		if (null == map || null == map.getResults() || map.getResults().size() < 1 || null == map.getResults().get(0).getLocation()) {
			return "未找到坐标";
		}
		return map.getResults().get(0).getLocation().getInfo();

	}

	@Override
	public Site getSite() {
		return site;
	}

	public static void main(String[] args) {
		System.out.println("harveynichols.com采集卡");
		Spider.create(new NewProcessor()).addUrl("http://www.harveynichols.com/mens-new-in/#/number_of_days_range/last_28_days/page/1").run();
	}
}